<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2018/1/9
 * Time: 10:23
 */
namespace common\services;
require  __DIR__ . '/wechat/vendor/autoload.php';
use EasyWeChat\Factory;

use Yii;

class WechatService{

    public function __construct()
    {
        $this->config       = Yii::$app->params['wx'];      // 获取微信相关配置
        $this->appId        = $this->config['appId'];       // 公众号ID
        $this->appSecret    = $this->config['appSecret'];   // 公众号key
        $this->redirectUri  = $this->config['redirectUri']; // 首页授权地址
//        $this->grantType    = $this->config['grantType'];   // 获取token参数
//        $this->mchId        = $this->config['mchId'];       // 商户id
//        $this->payKey       = $this->config['payKey'];      // 支付key
        $config = [
            'app_id' => $this->config['appId'],
//            'mch_id' => $this->config['mchId'],
            'secret' => $this->config['appSecret'],
//            'key'    => $this->config['payKey'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        $this->app = Factory::officialAccount($config);
    }

    public function wechat()
    {
        $oauth = $this->app->oauth;
//        $session = \Yii::$app->session;
        // 如果未获取到session（未登录）
        if (empty($_SESSION['wechat_user'])) {
            $_SESSION['target_url'] = 'goods-info/goods-home-page';
            $oauth->redirect()->send();
        }
        // 已登录（session中拿用户信息）
        $user = $_SESSION['wechat_user'];

    }

}